package com.jack.leetcode.array;

public class 移除元素 {

    public static void main(String[] args) {
        int[] nums = {3, 2, 2, 3};
        System.out.println(removeElement(nums, 3));
        int[] a = {0,1,2,2,3,0,4,2};
        System.out.println(removeElement(a, 2));
        int[] b = {0,1,2,2,3,0,4,2};
        System.out.println(removeElement(b, 2));
    }

    public static int removeElement(int[] nums, int val) {
        int n = nums.length;
        int result = 0;
        for (int i = 0; i < n; i++) {
            if (nums[i] != val) {
                result++;
            }
        }
        for (int i = 0; i < n; i++) {
            int endIndex = i + 1;
            if (nums[i] == val) {
                while (endIndex < n && nums[endIndex] == val) {
                    endIndex++;
                }
                if (endIndex == n) {
                    break;
                }
                switchValue(nums, i, endIndex);
            }
        }
        return result;
    }

    private static void switchValue(int[] nums, int left, int right) {
        int tmp = nums[left];
        nums[left] = nums[right];
        nums[right] = tmp;
    }
}
